/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using QName = System.Qizx.Api.QName;
using IQName = System.Qizx.Xdm.IQName;
using DynamicContext = System.Qizx.XQuery.DynamicContext;
using EvalContext = System.Qizx.XQuery.EvalContext;
using ExpressionImpl = System.Qizx.XQuery.ExpressionImpl;
using Focus = System.Qizx.XQuery.Focus;
using XQType = System.Qizx.XQuery.XQType;
using XQValue = System.Qizx.XQuery.XQValue;
using Function = System.Qizx.XQuery.Fn.Function;
using Prototype = System.Qizx.XQuery.Fn.Prototype;
namespace System.Qizx.XQuery.Ext
{
	
	/// <summary>  Parses and evaluates a XQuery expression.
	/// The expression is parsed in the global context of the current query
	/// or module, without access to local variables.
	/// </summary>
	public class XfnEval:ExtensionFunction
	{
		public override Prototype[] Protos
		{
			get
			{
				return protos;
			}
			
		}
		internal static QName qfname;
		internal static Prototype[] protos;
		
		public class Exec:Function.Call
		{
			public override XQValue eval(Focus focus, EvalContext context)
			{
				context.at(this);
				string src = args[0].evalAsString(focus, context);
				src = src.Replace('\r', ' ');
				ExpressionImpl expr = null;
				try
				{
					DynamicContext dynamicContext = context.dynamicContext();
					expr = dynamicContext.compileExpression(src);
					if (focus != null)
						expr.CurrentItem = focus.currentItem();
					
					// initialize globals of the expression from context globals:
					dynamicContext.passVariablesTo(expr);
					
					return expr.rawEval();
				}
				catch (EvaluationException e)
				{
					return context.error(this, e);
				}
				finally
				{
					// retrieve possible compilation messages
					//context.messages(expr.getMessages());
				}
			}
		}
		static XfnEval()
		{
			qfname = IQName.GetQName(EXTENSIONS_NS, "eval");
			protos = new Prototype[]{new Prototype(qfname, XQType.NODE.star, typeof(Exec)).arg("expression", XQType.STRING)};
		}
	}
}